/**
 * Copyright(C) 2008 Matthias Braunhofer
 * All rights reserved
 *
 * Created on: 26.07.2008
*/

package it.cums.ui.editors.product;

import it.cums.core.model.Product;
import it.cums.core.util.Converter;
import it.cums.core.util.ProductManager;
import it.cums.ui.actions.PrintAction;
import it.cums.ui.localization.Messages;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.ISaveablePart2;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.part.EditorPart;

public class ProductEditor extends EditorPart implements ISaveablePart2 {
	public static final String ID = "it.cums.editors.ProductEditor"; //$NON-NLS-1$
	private Button saveButton;
	private Button closeButton;
	private Text nameText;
	private Label errorNameLabel;
	private Text manufacturerText;
	private Text purchasingPriceText;
	private Label errorPurchasingPriceLabel;
	private Text salesPriceText;
	private Label errorSalesPriceLabel;
	private Text ivaText;
	private Label errorIvaLabel;
	private Text availableQuantityText;
	private Label errorAvailableQuantityLabel;
	private Text notesText;
	private Product product;
	private boolean changed;

	public ProductEditor() {
		// TODO Auto-generated constructor stub
	}

	
	public void doSave(IProgressMonitor monitor) {
		save();
	}

	
	public void doSaveAs() {
		// TODO Auto-generated method stub
	}

	
	public void init(IEditorSite site, IEditorInput input)
			throws PartInitException {
		setSite(site);
		setInput(input);
		setPartName(input.getName());
		
		// Enabling the global print button
		PrintAction printAction = new PrintAction(((ProductEditorInput)input).getProduct());
        site.getActionBars().setGlobalActionHandler(ActionFactory.PRINT.getId(),printAction);
        
        product = ((ProductEditorInput)input).getProduct();
	}

	
	public boolean isDirty() {
		// TODO Auto-generated method stub
		return changed;
	}

	
	public boolean isSaveAsAllowed() {
		// TODO Auto-generated method stub
		return false;
	}
	
	private void save() {
		int quantity = -1;
		if (getAvailableQuantity().length() != 0) {
			quantity = Converter.convertToInteger(getAvailableQuantity());
		} 
		double purchasingPrice = -1;
		if (getPurchasingPrice().length() != 0) {
			purchasingPrice = Converter.convertToDouble(getPurchasingPrice());
		} 
		ProductManager.getInstance().updateProduct(product, getName(), quantity, purchasingPrice, Converter.convertToInteger(getIva()), 
												   getManufacturer(), Converter.convertToDouble(getSalesPrice()), getNotes());  
		setChanged(false);
		firePropertyChange(EditorPart.PROP_DIRTY);
	}
	
	private void setChanged(boolean changed) {
		this.changed = changed;
		firePropertyChange(EditorPart.PROP_DIRTY);
	}

	
	public void createPartControl(Composite parent) {
		ScrolledComposite scrolledComposite = new ScrolledComposite(parent, SWT.V_SCROLL | SWT.H_SCROLL);
		Composite container = new Composite(scrolledComposite, SWT.NONE);
		GridLayout layout = new GridLayout(3,false);
		container.setLayout(layout);
		
		Composite commandControls = new Composite(container, SWT.NONE);
		GridLayout layout2 = new GridLayout(2, false);
		commandControls.setLayout(layout2);
		GridData layoutData = new GridData();
		layoutData.horizontalSpan = 3;
		commandControls.setLayoutData(layoutData);

		saveButton = new Button(commandControls, SWT.NONE);
		saveButton.setText(Messages.ProductEditor_1); 
		saveButton.addSelectionListener(new SelectionListener() {
			
			public void widgetDefaultSelected(SelectionEvent e) {
				// TODO Auto-generated method stub	
			}

			
			public void widgetSelected(SelectionEvent e) {
				if (isUserInputValid()) {
					save();
				}
			}});
		
		closeButton = new Button(commandControls, SWT.NONE);
		closeButton.setText(Messages.ProductEditor_2); 
		closeButton.addSelectionListener(new SelectionListener() {
			
			public void widgetDefaultSelected(SelectionEvent e) {
				// TODO Auto-generated method stub	
			}

			
			public void widgetSelected(SelectionEvent e) {
				IEditorPart current = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
				PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().closeEditor(current, true);
			}});
		
		GridData headerGrid = new GridData(GridData.FILL_HORIZONTAL);
		headerGrid.horizontalSpan = 3;
		headerGrid.verticalIndent = 15;
		
		Font boldFont = JFaceResources.getFontRegistry().getBold(JFaceResources.DEFAULT_FONT); 
		//Changed
		Label labelBasic = new Label(container, SWT.NONE);
		labelBasic.setText(Messages.ProductEditor_3); 
		labelBasic.setFont(boldFont);
		labelBasic.setLayoutData(headerGrid);
		
		Label label1 = new Label(container, SWT.NONE);
		label1.setText(Messages.ProductEditor_4); 
		GridData gd = new GridData(GridData.FILL_HORIZONTAL);
		nameText = new Text(container, SWT.BORDER | SWT.SINGLE);
		nameText.setLayoutData(gd);
		nameText.addModifyListener(new ModifyListener() {
			
			public void modifyText(ModifyEvent arg0) {
				setChanged(true);
				if (getName().length() == 0) {
					errorNameLabel.setVisible(true);
				} else {
					errorNameLabel.setVisible(false);
				}
				setPartName(getName());
			}});
		errorNameLabel = new Label(container, SWT.NONE);
		errorNameLabel.setText("*"); //$NON-NLS-1$
		errorNameLabel.setVisible(false);
		
		Label label2 = new Label(container, SWT.NONE);
		label2.setText(Messages.ProductEditor_5); 
		manufacturerText = new Text(container, SWT.BORDER | SWT.SINGLE);
		manufacturerText.setLayoutData(gd);
		manufacturerText.addModifyListener(new ModifyListener() {
			
			public void modifyText(ModifyEvent arg0) {
				setChanged(true);
			}});
		Label placeHolder = new Label(container, SWT.NONE);
		placeHolder.setText(""); //$NON-NLS-1$
		
		Label label3 = new Label(container, SWT.NONE);
		label3.setText(Messages.ProductEditor_6); 
		availableQuantityText = new Text(container, SWT.BORDER | SWT.SINGLE);
		availableQuantityText.setLayoutData(gd);
		availableQuantityText.addModifyListener(new ModifyListener() {
			
			public void modifyText(ModifyEvent arg0) {
				setChanged(true);
				if (getAvailableQuantity().length() != 0) {
					try {
						Converter.convertToInteger(getAvailableQuantity());
						errorAvailableQuantityLabel.setVisible(false);
					} catch (Exception e) {
						errorAvailableQuantityLabel.setVisible(true);
					}
				} else {
					errorAvailableQuantityLabel.setVisible(false);
				} 
			}});
		errorAvailableQuantityLabel = new Label(container, SWT.NONE);
		errorAvailableQuantityLabel.setText("*"); //$NON-NLS-1$
		errorAvailableQuantityLabel.setVisible(false);
		
		Label label4 = new Label(container, SWT.NONE);
		label4.setText(Messages.ProductEditor_7); 
		purchasingPriceText = new Text(container, SWT.BORDER | SWT.SINGLE);
		purchasingPriceText.setLayoutData(gd);
		purchasingPriceText.addModifyListener(new ModifyListener() {
			
			public void modifyText(ModifyEvent arg0) {
				setChanged(true);
				if (getPurchasingPrice().length() != 0) {
					try {
						Converter.convertToDouble(getPurchasingPrice());
						errorPurchasingPriceLabel.setVisible(false);
					} catch (Exception e) {
						errorPurchasingPriceLabel.setVisible(true);
					}
				} else {
					errorPurchasingPriceLabel.setVisible(false);
				} 
			}});
		errorPurchasingPriceLabel = new Label(container, SWT.NONE);
		errorPurchasingPriceLabel.setText("*"); //$NON-NLS-1$
		errorPurchasingPriceLabel.setVisible(false);
		
		Label label5 = new Label(container, SWT.NONE);
		label5.setText(Messages.ProductEditor_8); 
		ivaText = new Text(container, SWT.BORDER | SWT.SINGLE);
		ivaText.setLayoutData(gd);
		ivaText.addModifyListener(new ModifyListener() {
			
			public void modifyText(ModifyEvent arg0) {
				setChanged(true);
				if (getIva().length() == 0) {
					errorIvaLabel.setVisible(true);
				} else {
					try {
						Converter.convertToInteger(getIva());
						errorIvaLabel.setVisible(false);
					} catch (Exception e) {
						errorIvaLabel.setVisible(true);
					}
				}
			}});
		errorIvaLabel = new Label(container, SWT.NONE);
		errorIvaLabel.setText("*"); //$NON-NLS-1$
		errorIvaLabel.setVisible(false);
		
		Label label6 = new Label(container, SWT.NONE);
		label6.setText(Messages.ProductEditor_9); 
		salesPriceText = new Text(container, SWT.BORDER | SWT.SINGLE);
		salesPriceText.setLayoutData(gd);
		salesPriceText.addModifyListener(new ModifyListener() {
			
			public void modifyText(ModifyEvent arg0) {
				setChanged(true);
				if (getSalesPrice().length() == 0) {
					errorSalesPriceLabel.setVisible(true);
				} else {
					try {
						Converter.convertToDouble(getSalesPrice());
						errorSalesPriceLabel.setVisible(false);
					} catch (Exception e) {
						errorSalesPriceLabel.setVisible(true);
					}
				}
			}});
		errorSalesPriceLabel = new Label(container, SWT.NONE);
		errorSalesPriceLabel.setText("*"); //$NON-NLS-1$
		errorSalesPriceLabel.setVisible(false);
		
		Label label7 = new Label(container, SWT.NONE);
		label7.setText(Messages.ProductEditor_10); 
		GridData gridData = new GridData(GridData.FILL_BOTH);
		gridData.heightHint = 150;
		gridData.grabExcessVerticalSpace = false;
		notesText = new Text(container, SWT.BORDER | SWT.MULTI);
		notesText.setLayoutData(gridData);
		notesText.addModifyListener(new ModifyListener() {
			
			public void modifyText(ModifyEvent arg0) {
				setChanged(true);
			}});
		
		scrolledComposite.setContent(container);
		scrolledComposite.setExpandHorizontal(true);
		scrolledComposite.setExpandVertical(true);
		scrolledComposite.setMinSize(container.computeSize(SWT.DEFAULT, SWT.DEFAULT));
		
		initialize();
	}
	
	
	public void setFocus() {
		// TODO Auto-generated method stub
	}
	
	private void initialize() {
		nameText.setText(product.getName());
		manufacturerText.setText(product.getManufacturer());
		if (product.getPurchasingPrice() == -1) {
			purchasingPriceText.setText(""); //$NON-NLS-1$
		} else {
			purchasingPriceText.setText(String.valueOf(product.getPurchasingPrice()));
		}
		if (product.getAvailableQuantity() == -1) {
			availableQuantityText.setText(""); //$NON-NLS-1$
		} else {
			availableQuantityText.setText(String.valueOf(product.getAvailableQuantity()));
		}
		salesPriceText.setText(String.valueOf(product.getSalesPrice()));
		ivaText.setText(String.valueOf(product.getIva()));
		notesText.setText(product.getNotes());
		changed = false;
	}
	
	
	public void dispose() {
		super.dispose();
	}
	
	public int promptToSaveOnClose() {
		MessageDialog dialog = new MessageDialog(getEditorSite().getShell(), 
												Messages.ProductEditor_11,  
												null, 
												"'" + getTitle() + Messages.ProductEditor_12,  //$NON-NLS-1$ 
												MessageDialog.QUESTION, 
												new String[] {
												IDialogConstants.YES_LABEL, 
												IDialogConstants.NO_LABEL, 
												IDialogConstants.CANCEL_LABEL},
												0);
		final int dialogResult = dialog.open();
		
		if (dialogResult == 0) {
			if (isUserInputValid()) {
				return ISaveablePart2.YES;
			} else {
				return ISaveablePart2.CANCEL;
			}
		} else if (dialogResult == 1) {
			return ISaveablePart2.NO;
		} else {
			return ISaveablePart2.CANCEL;
		}
	}
	
	private String getName() {
		return nameText.getText().trim();
	}
	
	private String getManufacturer() {
		return manufacturerText.getText().trim();
	}
	
	private String getNotes() {
		return notesText.getText().trim();
	}
	
	private String getAvailableQuantity() {
		return availableQuantityText.getText().trim();
	}
	
	private String getPurchasingPrice() {
		return purchasingPriceText.getText().trim();
	}
	
	private String getSalesPrice() {
		return salesPriceText.getText().trim();
	}
	
	private String getIva() {
		return ivaText.getText().trim();
	}
	
	private boolean isUserInputValid() {
		if (getName().length() == 0) {
			return false;
		} 
		if (getIva().length() == 0) {
			return false;
		} else {
			try {
				Converter.convertToInteger(getIva());
			} catch (Exception e) {
				return false;
			}
		} 
		if (getPurchasingPrice().length() != 0) {
			try {
				Converter.convertToDouble(getPurchasingPrice());
			} catch (Exception e) {
				return false;
			}
		} 
		if (getSalesPrice().length() == 0) {
			return false;
		} else {
			try {
				Converter.convertToDouble(getSalesPrice());
			} catch (Exception e) {
				return false;
			}
		}
		if (getAvailableQuantity().length() != 0) {
			try {
				Converter.convertToInteger(getAvailableQuantity());
			} catch (Exception e) {
				return false;
			}
		}
		return true;
	}
}
